package com.example.show_auto.ui.pages

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.show_auto.ui.utils.OppoCompatibilityFix
import com.example.show_auto.viewmodel.MainViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.runtime.collectAsState

/**
 * 综合查询页面
 * 包含下拉框选择查询类型和一键查询按钮
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ComprehensiveQueryNewPage(
    onMenuClick: () -> Unit,
    onNavigateToTableProfit: () -> Unit,
    onNavigateToChefCategory: () -> Unit,
    modifier: Modifier = Modifier
) {
    // 获取 ViewModel 和游戏数据
    val viewModel: MainViewModel = viewModel()
    val gameData by viewModel.gameData.collectAsState()
    val uiState by viewModel.uiState.collectAsState()
    
    // 下拉框状态
    var selectedOption by remember { mutableStateOf<String?>(null) }
    var isDropdownExpanded by remember { mutableStateOf(false) }
    
    // 查询选项列表
    val queryOptions = listOf("桌子收益", "厨师分类")
    


    OppoCompatibilityFix.FixedLayoutContainer(
        modifier = modifier.fillMaxSize()
    ) {
        // 顶部应用栏
        TopAppBar(
            title = { 
                Text(text = "综合查询")
            },
            navigationIcon = {
                IconButton(onClick = onMenuClick) {
                    Icon(imageVector = Icons.Default.Menu, contentDescription = "菜单")
                }
            },
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                navigationIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer
            )
        )

        // 页面内容
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(OppoCompatibilityFix.getFixedSpacing(8.dp)),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // 查询选择区域 - 参考查询厨师修炼页面样式
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(
                        horizontal = 8.dp,
                        vertical = 4.dp
                    ),
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalAlignment = Alignment.Top
            ) {
                // 查询类型选择输入框（自定义实现）
                BoxWithConstraints(
                    modifier = Modifier
                        .weight(1f)
                        .padding(3.dp)
                ) {
                    val maxWidth = maxWidth
                    val textFieldInteractionSource = remember { MutableInteractionSource() }
                    
                    // 监听点击事件，点击任何地方都展开下拉框
                    LaunchedEffect(textFieldInteractionSource) {
                        textFieldInteractionSource.interactions.collect { interaction ->
                            when (interaction) {
                                is androidx.compose.foundation.interaction.PressInteraction.Press -> {
                                    if (selectedOption == null) {
                                        isDropdownExpanded = true
                                    }
                                }
                            }
                        }
                    }
                    
                    OutlinedTextField(
                        value = selectedOption ?: "",
                        onValueChange = { },
                        readOnly = true,
                        label = { Text("选择查询类型", fontSize = 11.sp) },
                        placeholder = { 
                            Text(
                                "点击选择查询类型", 
                                fontSize = 10.sp, 
                                lineHeight = 16.sp,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            ) 
                        },
                        leadingIcon = {
                            Icon(
                                imageVector = Icons.Default.Search,
                                contentDescription = "查询",
                                modifier = Modifier.size(20.dp)
                            )
                        },
                        trailingIcon = {
                            Row(
                                modifier = Modifier
                                    .width(48.dp) // 固定宽度，确保收起按钮位置不变
                                    .offset(x = (-8).dp), // 整体向左移动8dp
                                horizontalArrangement = Arrangement.End,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                // 清除按钮
                                if (selectedOption != null) {
                                    IconButton(
                                        onClick = {
                                            selectedOption = null
                                            isDropdownExpanded = false
                                        },
                                        modifier = Modifier.size(20.dp)
                                    ) {
                                        Icon(
                                            imageVector = Icons.Default.Clear,
                                            contentDescription = "清除",
                                            modifier = Modifier.size(14.dp)
                                        )
                                    }
                                }

                                // 展开/收起按钮 - 始终在最右侧
                                IconButton(
                                    onClick = {
                                        isDropdownExpanded = !isDropdownExpanded
                                    },
                                    modifier = Modifier.size(24.dp)
                                ) {
                                    Icon(
                                        imageVector = if (isDropdownExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                                        contentDescription = if (isDropdownExpanded) "收起" else "展开",
                                        modifier = Modifier.size(18.dp)
                                    )
                                }
                            }
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(55.dp)
                            .clickable(
                                interactionSource = textFieldInteractionSource,
                                indication = null
                            ) {
                                if (selectedOption == null) {
                                    isDropdownExpanded = true
                                }
                            },
                        singleLine = true,
                        textStyle = androidx.compose.ui.text.TextStyle(fontSize = 12.sp),
                        colors = OutlinedTextFieldDefaults.colors(
                            focusedBorderColor = MaterialTheme.colorScheme.primary,
                            unfocusedBorderColor = MaterialTheme.colorScheme.outline
                        ),
                        interactionSource = textFieldInteractionSource
                    )
                }
                
                // 一键查询按钮
                Button(
                    onClick = {
                        when (selectedOption) {
                            "桌子收益" -> onNavigateToTableProfit()
                            "厨师分类" -> onNavigateToChefCategory()
                            else -> { /* 其他查询类型的处理逻辑 */ }
                        }
                    },
                    modifier = Modifier
                        .height(50.dp)
                        .offset(y = 9.dp),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary,
                        contentColor = MaterialTheme.colorScheme.onPrimary
                    ),
                    shape = RoundedCornerShape(8.dp),
                    contentPadding = PaddingValues(horizontal = 16.dp, vertical = 0.dp),
                    enabled = selectedOption != null && gameData != null && uiState.isDataLoaded
                ) {
                    Text(
                        "一键查询",
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Medium
                    )
                }
            }
            
                         // 下拉框覆盖层 - 显示在Row外部，确保在最顶层，参考查询厨师修炼页面样式
             if (isDropdownExpanded) {
                 Column(
                     modifier = Modifier
                         .fillMaxWidth()
                         .padding(horizontal = 11.dp) // 与搜索框对齐，减少边距
                         .offset(y = (-8).dp) // 向上偏移，紧贴搜索框
                 ) {
                    // 查询类型列表卡片
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .heightIn(max = 400.dp),
                        elevation = CardDefaults.cardElevation(defaultElevation = 16.dp)
                    ) {
                        if (queryOptions.isNotEmpty()) {
                            LazyColumn {
                                items(queryOptions) { option ->
                                    Column(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .clickable {
                                                selectedOption = option
                                                isDropdownExpanded = false
                                            }
                                            .padding(start = 16.dp, top = 16.dp, bottom = 16.dp, end = 8.dp)
                                    ) {
                                                                                 // 查询类型标题和描述（一行展示）
                                         Row(
                                             modifier = Modifier.fillMaxWidth(),
                                             verticalAlignment = Alignment.CenterVertically
                                         ) {
                                             // 左侧：查询类型标题（固定宽度）
                                             Text(
                                                 text = option,
                                                 fontSize = 12.sp,
                                                 fontWeight = FontWeight.Medium,
                                                 color = MaterialTheme.colorScheme.onSurface,
                                                 modifier = Modifier.width(80.dp)
                                             )
                                             
                                             Spacer(modifier = Modifier.width(16.dp))
                                             
                                             // 右侧：查询类型描述（左对齐）
                                             Text(
                                                                                              text = when (option) {
                                                 "桌子收益" -> "查询桌子的收益情况"
                                                 "厨师分类" -> "查询厨师的分类信息"
                                                 else -> "更多查询功能正在开发中"
                                             },
                                                 fontSize = 10.sp,
                                                 color = MaterialTheme.colorScheme.onSurfaceVariant,
                                                 lineHeight = 12.sp,
                                                 modifier = Modifier.weight(1f)
                                             )
                                         }
                                    }
                                    // 添加横隔线（除了最后一个项目）
                                    if (option != queryOptions.last()) {
                                        HorizontalDivider(
                                            modifier = Modifier.padding(horizontal = 16.dp),
                                            color = MaterialTheme.colorScheme.outline.copy(alpha = 0.2f)
                                        )
                                    }
                                }
                            }
                        } else {
                            // 空状态
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(32.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = "暂无可用的查询类型",
                                    fontSize = 14.sp,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    }
                }
            }
        }
    }
} 